from app.services.business.gaolu_diagnose.ind.abstract_ind import AbstractInd


class CG_LT_GL_GL04_Rtiecha(AbstractInd):

    def get_name(self):
        return "CG_LT_GL_GL04_Rtiecha"

    def get_data_source(self):
        return "mysql"

    def get_sql(self, params):
        return """      
        SELECT
            t1.fnumber,
            t1.fdate,
            t2.tieliang
        FROM
        (SELECT
            cg.syn_tq_rgaoluchutie.fnumber,
            cg.syn_tq_rgaoluchutie.fdate
        FROM  cg.syn_tq_rgaoluchutie  where fdate >"{dt_start}")t1
            JOIN 
        (SELECT
            fnumber,
            SUM(fquantity) as tieliang
            FROM cg.syn_tq_rtieguan where fdatetime > "{dt_start}"
            GROUP BY fnumber)t2
            on t1.fnumber = t2.fnumber
        """.format(**params)

    @AbstractInd.cache_wrapper
    def get_result(self):
        sql: str = self.get_sql(self.params)
        cursor = self.mysql_cursor
        cursor.execute(sql)
        results = cursor.fetchall()

        latest_date = None
        latest_value = 0
        # 差值和
        d_value_sum = 0

        # 差值数
        d_value_count = 0

        for index, result in enumerate(results):
            if index == 0:
                latest_date = result['fdate']
                latest_value = result['tieliang']
                continue

            if latest_date == result['fdate']:
                current_value = result['tieliang']
                v = abs(current_value - latest_value)
                d_value_sum = d_value_sum + v
                d_value_count = d_value_count + 1

        if d_value_sum == 0 and d_value_count == 0: return 0

        return d_value_sum / d_value_count
